<?php

namespace AdminModule;

use \AdminModule\Helpers\Image;

class ZboziPresenter extends \AdminModule\AdminPresenter {

    public function actionDefault() {
        $this->template->tiles = new Models\Tile($this->db);
    }

    public function actionPridat() {
        ;
    }

    public function actionUpravit($id) {
        $tileModel = new Models\Tile($this->db);
        $tile = $tileModel->get($id);
        if (!$tile) {
            $this->flashMessage('Zboží s požadovaným id neexistuje', 'error');
            $this->redirect('default');
        }
        $this->template->imageTool = new \AdminModule\Tools\Image($this->db);
        $this->template->image = $tile->image;
    }

    public function handleSmazat($id) {
        $tileModel = new Models\Tile($this->db);
        $tile = $tileModel->get($id);
        if ($tile instanceof \Nette\Database\Table\ActiveRow) {
            try {
                $imageModel = new \AdminModule\Models\Image($this->db);
                $imageModel->deleteImageFile($tile->image);            
                $tile->delete();
                $this->flashMessage('Zboží bylo smazáno', 'info');
            } catch (\LogicException $exception) {
                $this->flashMessage('Zboží se nepodařilo smazat (' . $exception->getMessage() . ')', 'error');
            }
        } else {
            $this->flashMessage('Zboží se zadaným id nebylo nalezeno', 'error');
        }
        $this->invalidateControl('content');
        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    public function handlePridat($id) {
        $showroomHasTileModel = new \AdminModule\Models\ShowroomHasTiles($this->db);
        $inShowrooms = $showroomHasTileModel->where('id_tile = ?', $id);
        
        if (\count($inShowrooms) > 0) {
            $this->flashMessage('Položku se nepodařilo přidat akcí, protože je součástí nějaké kóje.', 'error');
        } else if ($this->setAction($id, true)) {
            $this->flashMessage('Položka byla přidána do akcí');
        } else {
            $this->flashMessage('Přidání do akcí se nezdařilo', 'error');
        }
        $this->invalidateControl('content');
        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    public function handleOdebrat($id) {
        if ($this->setAction($id, false)) {
            $this->flashMessage('Položka byla odstraněna z akcí');
        } else {
            $this->flashMessage('Odebrání z akcí se nezdařilo', 'error');
        }
        $this->invalidateControl('content');
        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    private function setAction($id, $isAction) {
        $tileModel = new Models\Tile($this->db);
        $tile = $tileModel->get($id);
        $operationSuccess = false;        
        if ($tile instanceof \Nette\Database\Table\ActiveRow) {
            $operationSuccess = $tile->update(array('action' => $isAction));
        }
        
        return $operationSuccess;
    }

    protected function createComponentTileForm() {
        $form = new \Nette\Application\UI\Form;

        $manufacturer = new Models\Manufacturer($this->db);
        $manufacturersOptions = $manufacturer->getSelectOptions();

        $tileType = new Models\TileType($this->db);
        $tileTypesOptions = $tileType->getSelectOptions();

        $form->addSelect('id_manufacturer', 'Výrobce', $manufacturersOptions);
        $form->addText('code', 'Kód')
                ->setRequired('Zadejte kód');
        $form->addSelect('id_tile_type', 'Typ', $tileTypesOptions);
        $form->addText('width', 'Šířka [cm]')
                ->setRequired('Zadejte šířku')
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Šířka musí být platné číslo');
        $form->addText('height', 'Výška [cm]')
                ->setRequired('Zadejte výšku')
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Výška musí být platné číslo');
        $form->addText('price', 'Cena')
                ->setRequired('Zadejte cenu')
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Cena musí být číslo');
        $form->addHidden('type')->setValue(Image::TYPE_TILE);
        $image = $form->addUpload('image', 'Obrázek');

        if ($this->action == 'upravit') {
            $tileModel = new Models\Tile($this->db);
            $tile = $tileModel->get($this->getParameter('id'));
            $form->setDefaults($tile);
            $form->addHidden('id_image')->setValue($tile->image->id_image);
            $form->addSubmit('add', 'Uložit');
        } else {
            $image->setRequired('Vyberte obrázek');
            $form->addSubmit('add', 'Přidat');
        }

        $form->onSuccess[] = $this->tileFormSubmitted;
        return $form;
    }

    /**
     * Zpracobvani formulare pro pridani/upraveni nabidky.
     * 
     * @param \Nette\Application\UI\Form $form
     */
    public function tileFormSubmitted(\Nette\Application\UI\Form $form) {
        $values = $form->getValues(true);
        $this->db->beginTransaction();
        $imageModel = new Models\Image($this->db);
        $tileModel = new Models\Tile($this->db);

        try {
            if ($this->action == 'pridat') {
                $insertedImage = $imageModel->insert($values);
                $values['id_image'] = $insertedImage->id_image;
                $tileModel->insert($values);
                $this->flashMessage('Položka byla přidána');
                $this->db->commit();
                $this->redirect('Zbozi:default');
            } else {
                $tile = $tileModel->get($this->getParameter('id'));
                $image = $imageModel->update($values);
                $values['id_image'] = $image->id_image;
                $tile->update($tileModel->filter($values));
                $this->flashMessage('Položka byla upravena');
                $this->db->commit();
                $this->redirect('this');
            }
        } catch (\LogicException $exception) {
            $this->db->rollback();
            $form->addError('Uložení se nepodařilo ' . $exception->getMessage());
        }
    }

}
